package com.dingtalk.yuanhua_spring_project.service.impl;

import com.aliyun.dingtalkstorage_1_0.Client;
import com.aliyun.dingtalkstorage_1_0.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.yuanhua_spring_project.service.DingTalkDingPan;
import com.dingtalk.yuanhua_spring_project.service.DingTalkStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Service public class DingTalkStorageimpl implements DingTalkStorage {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkStorageimpl.class);
    @Autowired
    private DingTalkDingPanimpl dingTalkDingPanimpl;
    @Value("${union_id}")
    private String unionId;
    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }
    /**
    * 获取所有文件夹信息
    * */
    @Override
    public Map<String, Map<String, String>> getFolderList(String accessToken, String spaceid) throws Exception {
        logger.debug("Starting to get folder list for spaceId: {}", spaceid);
        Client client = createClient();
        ListAllDentriesHeaders listAllDentriesHeaders = new ListAllDentriesHeaders();
        listAllDentriesHeaders.xAcsDingtalkAccessToken = accessToken; // 使用传入的 accessToken
        ListAllDentriesRequest listAllDentriesRequest = new ListAllDentriesRequest()
                .setUnionId("LgiPFZRlsXceenh4GiieLoaQiEiE"); // 确保 unionId 正确

        Map<String, Map<String, String>> folderMap = new HashMap<>();
        String nextToken = null;

        do {
            if (nextToken != null) {
                ListAllDentriesRequest.ListAllDentriesRequestOption option = new com.aliyun.dingtalkstorage_1_0.models.ListAllDentriesRequest.ListAllDentriesRequestOption()
                        .setNextToken(nextToken);
                listAllDentriesRequest.setOption(option);
            }

            try {
                var response = client.listAllDentriesWithOptions(spaceid, listAllDentriesRequest, listAllDentriesHeaders, new RuntimeOptions()).getBody();
                var dentriesList = response.getDentries();
                nextToken = response.getNextToken();

                for (var dentry : dentriesList) {
                    String name = dentry.getName();
                    String parentid = dentry.getParentId();
                    String path = dentry.getPath();
                    String uuid = dentry.getUuid();
                    String id = dentry.getId();

                    Map<String, String> folderInfo = new HashMap<>();
                    folderInfo.put("parentid", parentid);
                    folderInfo.put("name", name);
                    folderInfo.put("uuid", uuid);
                    folderInfo.put("id", id);

                    folderMap.put(path, folderInfo);
                }
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
                    break; // 出现错误时退出循环
                }
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
                    break; // 出现错误时退出循环
                }
            }
        } while (nextToken != null);
        logger.debug("Finished getting folder list for spaceId: {}", spaceid);
        return folderMap;
    }


    /**
     * 如果不存在当前文件夹就添加文件夹
     */
    @Override
    public void addFolder(String fileName, String spaceid, String parentId,String accessToken) throws Exception {
        logger.debug("Starting to add folder for spaceId: {} for parentId: {}", spaceid, parentId);
        Client client = createClient();
        AddFolderHeaders addFolderHeaders = new AddFolderHeaders();
        addFolderHeaders.xAcsDingtalkAccessToken = accessToken; // 使用传入的 accessToken
        AddFolderRequest addFolderRequest = new AddFolderRequest()
                .setUnionId("LgiPFZRlsXceenh4GiieLoaQiEiE") // 确保 unionId 正确
                .setName(fileName);
        try {
            client.addFolderWithOptions(spaceid, parentId, addFolderRequest, addFolderHeaders, new RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }
        }
    }

    /**
     获取上传文件信息
     */
    public String getUploadFileInfoBySpaceId(String accessToken, String spaceid) throws Exception {
        String uploadFileUrl = "";
        Client client = createClient();
        GetFileUploadInfoHeaders getFileUploadInfoHeaders = new GetFileUploadInfoHeaders();
        getFileUploadInfoHeaders.xAcsDingtalkAccessToken = accessToken;
        GetFileUploadInfoRequest getFileUploadInfoRequest = new GetFileUploadInfoRequest()
                .setProtocol("HEADER_SIGNATURE")
                .setMultipart(false);
        try {
            uploadFileUrl = client.getFileUploadInfoWithOptions(spaceid, getFileUploadInfoRequest, getFileUploadInfoHeaders, new RuntimeOptions()).getBody().getHeaderSignatureInfo().getResourceUrls().getFirst();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        return uploadFileUrl;
    }

    public static com.aliyun.dingtalkstorage_2_0.Client createClient2() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkstorage_2_0.Client(config);
    }

    @Override public String GetFileUploadInfoByDentryId(String accessToken, String dentryId, String fileSaveUrl, String fileName) throws Exception {
        logger.debug("开始获取文件上传信息: {}", dentryId);
        String uploadFileUrl = "";
        com.aliyun.dingtalkstorage_2_0.Client client = createClient2();
        com.aliyun.dingtalkstorage_2_0.models.GetFileUploadInfoHeaders getFileUploadInfoHeaders = new com.aliyun.dingtalkstorage_2_0.models.GetFileUploadInfoHeaders();
        getFileUploadInfoHeaders.xAcsDingtalkAccessToken = accessToken;
        com.aliyun.dingtalkstorage_2_0.models.GetFileUploadInfoRequest getFileUploadInfoRequest = new com.aliyun.dingtalkstorage_2_0.models.GetFileUploadInfoRequest()
                .setProtocol("HEADER_SIGNATURE").setUnionId("LgiPFZRlsXceenh4GiieLoaQiEiE");
        try {
            var response = client.getFileUploadInfoWithOptions(dentryId, getFileUploadInfoRequest, getFileUploadInfoHeaders, new com.aliyun.teautil.models.RuntimeOptions()).getBody();
            var header = response.getHeaderSignatureInfo().getHeaders();
            uploadFileUrl = response.getHeaderSignatureInfo().getResourceUrls().getFirst();
            uploadFile1(header, uploadFileUrl, fileSaveUrl);
            uploadFile(fileName, accessToken, dentryId,response.getUploadKey());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        }
        logger.debug("获取文件上传信息成功: {}", uploadFileUrl);
        return uploadFileUrl;
    }

    @Override
    public String getAccessToken() {
        return new DingTalkAccessimpl().getAccessToken();
    }

    public void uploadFile1(Map<String, String> headers , String uploadKey, String fileSaveUrl) throws IOException {
        logger.debug("开始上传文件到阿里云: {}", fileSaveUrl);
        URL url = new URL(uploadKey);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        System.out.println(uploadKey);
        System.out.println(headers);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setUseCaches(false);
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(10000);
        connection.connect();
        OutputStream out = connection.getOutputStream();
        InputStream is = new FileInputStream(fileSaveUrl);
        byte[] b =new byte[1024];
        int temp;
        while ((temp=is.read(b))!=-1){
            out.write(b,0,temp);
        }
        out.flush();
        out.close();
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        if (responseCode == 200) {
            logger.debug("上传文件成功: {}", fileSaveUrl);
        } else {
            logger.debug("上传文件失败: {}", fileSaveUrl);
        }
        logger.debug("结束上传文件到阿里云: {}", fileSaveUrl);
    }

    /**
    * 上传文件
    * */
    public void uploadFile(String fileName, String accessToken, String parentId, String uploadKey) throws Exception {
        logger.debug("开始上传文件到钉盘: {}", fileName);
        com.aliyun.dingtalkstorage_2_0.Client client = createClient2();
        com.aliyun.dingtalkstorage_2_0.models.CommitFileHeaders commitFileHeaders = new com.aliyun.dingtalkstorage_2_0.models.CommitFileHeaders();
        commitFileHeaders.xAcsDingtalkAccessToken = accessToken;
        com.aliyun.dingtalkstorage_2_0.models.CommitFileRequest commitFileRequest = new com.aliyun.dingtalkstorage_2_0.models.CommitFileRequest()
                .setUnionId("LgiPFZRlsXceenh4GiieLoaQiEiE")
                .setUploadKey(uploadKey)
                .setName(fileName);
        try {
            client.commitFileWithOptions(parentId, commitFileRequest, commitFileHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        }
        logger.debug("开始上传文件到钉盘: {}", fileName);
    }

    public void addPermission(String accessToken, String userid, String FolderUUid) throws Exception {
        logger.debug("开始给用户添加权限: {}", userid);
        com.aliyun.dingtalkstorage_2_0.Client client = createClient2();
        com.aliyun.dingtalkstorage_2_0.models.AddPermissionHeaders addPermissionHeaders = new com.aliyun.dingtalkstorage_2_0.models.AddPermissionHeaders();
        addPermissionHeaders.xAcsDingtalkAccessToken = accessToken;
        com.aliyun.dingtalkstorage_2_0.models.AddPermissionRequest.AddPermissionRequestMembers members0 = new com.aliyun.dingtalkstorage_2_0.models.AddPermissionRequest.AddPermissionRequestMembers()
                .setType("USER")
                .setId(userid);
        com.aliyun.dingtalkstorage_2_0.models.AddPermissionRequest addPermissionRequest = new com.aliyun.dingtalkstorage_2_0.models.AddPermissionRequest()
                .setRoleId("DOWNLOADER")
                .setUnionId(unionId)
                .setMembers(java.util.Arrays.asList(
                        members0
                ));
        try {
            client.addPermissionWithOptions(FolderUUid, addPermissionRequest, addPermissionHeaders, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("Error code: {}, Error message: {}", err.code, err.message, err);
            }

        }
    }

}
